package cn.mengfly.testnrz.im.client.sender;

import cn.mengfly.testnrz.im.ProtoMsg;
import cn.mengfly.testnrz.im.client.ClientSession;
import cn.mengfly.testnrz.im.client.bean.User;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import lombok.Data;

@Data
public abstract class BaseSender {

    private User user;
    private ClientSession session;

    public boolean isConnected() {
        if (checkSession()) {
            return session.isConnected();
        }
        return false;
    }

    public boolean isLogin() {
        if (checkSession()) {
            return session.isLogin();
        }
        return false;
    }

    public void sendMsg(final ProtoMsg.Message message) {
        if (!isConnected()) {
            System.out.println("连接还没有成功");
            return;
        }
        Channel channel = getSession().getChannel();
        ChannelFuture f = channel.writeAndFlush(message);
        f.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) {
                if (future.isSuccess()) {
                    sendSuccess(message);
                } else {
                    sendFailed(message);
                }
            }
        });
    }

    protected void sendSuccess(ProtoMsg.Message message) {
        System.out.println("发送成功");
    }

    protected void sendFailed(ProtoMsg.Message message) {
        System.out.println("发送失败");
    }


    public boolean checkSession() {
        if (session == null) {
            System.out.println("session is null");
            return false;
        }
        return true;
    }
}
